
package at.fhj.ase.clientarch.server.db.dao.impl;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.ase.clientarch.common.util.StringUtil;
import at.fhj.ase.clientarch.server.db.dao.UserDAO;
import at.fhj.ase.clientarch.server.db.hibernate.entities.EntityUser;

/**
 * @author cja, sfe | www.fh-joanneum.at | Client Architectures and Design
 */
public class UserDAOImpl extends GenericDAOImpl<EntityUser, Long> implements UserDAO {
  private final Logger logger = LoggerFactory.getLogger(getClass().getName());

  /** Constructor - make this class only usable to {@link DatabaseController} */
  UserDAOImpl() {
    super();
  }

  @Override
  public EntityUser findByUsernamePassword(final String username, final String password) {
    // make sure that there are no useless database operations performed
    if (StringUtil.isEmptyOrNull(username) || StringUtil.isEmptyOrNull(password)) {
      return null;
    }

    Query query = getEntityManager().createQuery("FROM EntityUser u WHERE u.username = ?1 and u.password = ?2");
    query = query.setParameter(1, username);
    query = query.setParameter(2, password);

    try {
      return (EntityUser) query.getSingleResult(); // could be null
    } catch (NoResultException nre) {
      logger.warn("Unable to find a result for username '" + username + "'");
      // TODO each other throwable (!) should be caugt outside and not "purely" given back to clients. otherwise we don't see it on server at all
      
      return null;
    }
  }
}
